package cc.sheji.Service;


import cc.sheji.domain.Device;
import cc.sheji.domain.DeviceQueryCriteria;
import cc.sheji.domain.MessageCode;
import cc.sheji.reposity.DeviceRepository;
import cc.sheji.util.QueryHelp;
import cn.hutool.core.util.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class MessageCodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    SendSms sendSms;

    public MessageCode create(MessageCode entity) throws Exception {

        int random=   new Random().nextInt(1000)+1000;

        redisTemplate.opsForValue().set("code"+entity.getPhone(), ""+random, 5, TimeUnit.MINUTES);

        entity.setId(IdUtil.getSnowflakeNextId());
        entity.setCode(""+random);
        if(entity.getPhone().length()==11){
            sendSms.send(entity.getPhone(), entity.getCode());
        }
        return entity;
    }

    public MessageCode get(@PathVariable("id") Long id) {


        MessageCode entity=new MessageCode();
        entity.setId(id);
        entity.setCode("1234");
        return entity;
    }

    public boolean check(MessageCode entity){

        System.out.println(entity);
        String code = "" + redisTemplate.opsForValue().get("code" + entity.getPhone());
        if(code.equals("null")||code.isEmpty()){
            return  false;
        }
        if(entity.getCode().equals(code)){
            return true;
        }else {
            return  false;
        }
    }
}
